package com.jvyou.proxy.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author 橘柚
 * @version 1.0-SNAPSHOT
 * @Date 2024/5/23 21:47
 * @Description cglib动态代理
 */
public class CglibProxy implements MethodInterceptor {

    /**
     * 获取代理对象，不需要依赖实现的接口
     *
     * @param clazz 目标对象类型
     * @param <T>   目标对象的类型
     * @return 代理对象
     */
    @SuppressWarnings("unchecked")
    public <T> T getInstance(Class<T> clazz) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(this);
        return (T) enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("cglib代理开始");
        Object result = methodProxy.invokeSuper(o, objects);
        System.out.println("cglib代理结束");
        return result;
    }
}
